<template>
  <div class="common-layout">
    <el-container>
      <el-header>
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
          <el-form-item label="部门名称">
            <el-input v-model="formInline.departmentName" placeholder="请输入部门名称" clearable />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">查询</el-button>
            <el-button type="primary" @click="openAddDialog" v-if="isAdmin">新增部门</el-button>
          </el-form-item>
        </el-form>
      </el-header>
      <el-main>
        <el-table :data="tableData" border style="width: 100%">
          <el-table-column type="index" label="序号" width="80" />
          <el-table-column prop="departmentName" label="部门名称" width="150" />
          <el-table-column prop="parentId" label="上级部门" width="150">
            <template #default="scope">
              {{ scope.row.parentName || '无' }}
            </template>
          </el-table-column>
          <el-table-column prop="description" label="部门描述" width="200" />
          <el-table-column fixed="right" label="操作" min-width="120">
            <template #default="scope">
              <el-button type="primary" @click="openEditDialog(scope.row)">编辑</el-button>
              <el-button type="danger" @click="handleDelete(scope.row)" v-if="isAdmin">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 新增/编辑部门弹窗 -->
        <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑部门' : '新增部门'" width="500px">
          <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
            <el-form-item label="部门名称" prop="departmentName">
              <el-input v-model="formData.departmentName" placeholder="请输入部门名称" />
            </el-form-item>
            <el-form-item label="上级部门" prop="parentId">
              <el-select v-model="formData.parentId" placeholder="请选择上级部门">
                <el-option label="无" value="0" />
                <el-option v-for="dept in allDepartments" :key="dept.id" :label="dept.departmentName" :value="dept.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="部门描述" prop="description">
              <el-input v-model="formData.description" placeholder="请输入部门描述" />
            </el-form-item>
          </el-form>
          <template #footer>
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitForm">确认</el-button>
          </template>
        </el-dialog>
      </el-main>
    </el-container>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import { useCounterStore } from '@/stores/counter';

// 状态管理
const pinia = useCounterStore();
const isAdmin = pinia.piniaDto.roleName === '管理员';

// 筛选表单
const formInline = reactive({
  departmentName: ''
});

// 表格数据 - 本地模拟
const tableData = ref([
  {
    id: 1,
    departmentName: '总经办',
    parentId: 0,
    parentName: '无',
    description: '公司最高决策部门'
  },
  {
    id: 2,
    departmentName: '研发部',
    parentId: 1,
    parentName: '总经办',
    description: '负责产品研发'
  },
  {
    id: 3,
    departmentName: '质检部',
    parentId: 1,
    parentName: '总经办',
    description: '负责产品质量检测'
  }
]);

// 所有部门（用于下拉选择）
const allDepartments = ref([
  { id: 1, departmentName: '总经办' },
  { id: 2, departmentName: '研发部' },
  { id: 3, departmentName: '质检部' }
]);

// 弹窗相关
const dialogVisible = ref(false);
const isEdit = ref(false);
const formRef = ref<FormInstance>();
const formData = reactive({
  id: 0,
  departmentName: '',
  parentId: 0,
  description: ''
});

// 表单校验规则
const rules = reactive({
  departmentName: [{ required: true, message: '请输入部门名称', trigger: 'blur' }]
});

// 页面初始化
onMounted(() => {
  // 初始加载数据
});

// 查询部门列表（本地筛选）
const onSubmit = () => {
  const filterText = formInline.departmentName.toLowerCase();
  if (!filterText) {
    // 恢复原始数据
    tableData.value = [
      {
        id: 1,
        departmentName: '总经办',
        parentId: 0,
        parentName: '无',
        description: '公司最高决策部门'
      },
      {
        id: 2,
        departmentName: '研发部',
        parentId: 1,
        parentName: '总经办',
        description: '负责产品研发'
      },
      {
        id: 3,
        departmentName: '质检部',
        parentId: 1,
        parentName: '总经办',
        description: '负责产品质量检测'
      }
    ];
    return;
  }
  
  // 本地筛选
  tableData.value = tableData.value.filter(item => 
    item.departmentName.toLowerCase().includes(filterText)
  );
};

// 打开弹窗
const openAddDialog = () => {
  isEdit.value = false;
  formData.id = 0;
  formData.departmentName = '';
  formData.parentId = 0;
  formData.description = '';
  dialogVisible.value = true;
};

const openEditDialog = (row: any) => {
  isEdit.value = true;
  formData.id = row.id;
  formData.departmentName = row.departmentName;
  formData.parentId = row.parentId;
  formData.description = row.description;
  dialogVisible.value = true;
};

// 提交表单（本地处理）
const submitForm = () => {
  if (!formRef.value) return;
  
  formRef.value.validate(valid => {
    if (valid) {
      if (isEdit.value) {
        // 编辑操作
        const index = tableData.value.findIndex(item => item.id === formData.id);
        if (index !== -1) {
          tableData.value[index] = { ...formData, parentName: allDepartments.value.find(d => d.id === formData.parentId)?.departmentName || '无' };
          ElMessage.success('部门更新成功');
        }
      } else {
        // 新增操作
        const newId = Math.max(...tableData.value.map(item => item.id)) + 1;
        const parentName = allDepartments.value.find(d => d.id === formData.parentId)?.departmentName || '无';
        tableData.value.push({ ...formData, id: newId, parentName });
        allDepartments.value.push({ id: newId, departmentName: formData.departmentName });
        ElMessage.success('部门新增成功');
      }
      dialogVisible.value = false;
    }
  });
};

// 删除部门
const handleDelete = (row: any) => {
  ElMessageBox.confirm(
    `确认删除部门"${row.departmentName}"吗？`,
    '删除确认',
    { type: 'warning' }
  ).then(() => {
    // 本地删除
    tableData.value = tableData.value.filter(item => item.id !== row.id);
    allDepartments.value = allDepartments.value.filter(item => item.id !== row.id);
    ElMessage.success('部门删除成功');
  });
};
</script>

<style scoped>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.el-header {
  padding: 16px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #e5e7eb;
}

.el-main {
  padding: 16px;
}

.el-table {
  margin-bottom: 16px;
}
</style>